/*
 * @Description: 创建描述节点弹窗
 * @Author: Rfan
 * @Date: 2022-06-28 20:35:00
 * @LastEditTime: 2022-07-06 19:47:43
 */

import { FC, useEffect } from 'react';
import { Button, Form, Input, Modal } from 'antd';
import { ICommonDialog } from '@/interfaces/global';
import { IFolderTreeNode } from '@/interfaces/folderTree';
import { IEditTreeNodeParams } from '@/api/floderTree';
import { useFolderTreeContext } from '../../contexts/FolderTreeContext';
import { jsonClone } from '@/utils';

interface IRenameNodeDialogProps extends ICommonDialog {
  node: IFolderTreeNode | null;
  title?: string;
}

const RenameNodeDialog: FC<IRenameNodeDialogProps> = (props) => {
  const { visible, node, title = '重命名节点', onClose } = props;
  const { editTreeNodeFunc } = useFolderTreeContext();
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      const _node = jsonClone(node);
      _node.name = _node.nodeName;
      form.setFieldsValue(_node);
    }
  }, [visible]);

  /**
   * @description: 关闭弹窗方法
   */
  const onCancel = () => {
    onClose();
  };

  /**
   * @description: 提交表单方法
   * @param {{ nodeName: string; remark: string }} vals 表单数据
   */
  const onFinish = (vals: { name: string; remark: string }) => {
    if (node && node.id) {
      const params: IEditTreeNodeParams = {
        nodeName: vals.name,
        id: node.id
      };
      editTreeNodeFunc(params).then(() => {
        onClose();
      });
    }
  };

  return (
    <Modal
      title={title}
      visible={visible}
      width={400}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="save"
          type="primary"
          onClick={() => {
            form.submit();
          }}
        >
          保存
        </Button>
      ]}
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        preserve={false}
        onFinish={onFinish}
      >
        <Form.Item name="name" label="节点名称" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default RenameNodeDialog;
